﻿using System;
using System.Collections.Generic;
using System.Reflection;
using System.Text;
using System.Threading;

namespace Framework.Domain.Interface.DomainObject.UnitOfWork
{
    /// <summary>
    /// 工作单元工厂类
    /// ThreadLocal 每个线程中公用一个工作单元
    /// GetAppUnitOfWorkRepository 保证线程内唯一
    /// </summary>
    public class AppUnitOfWorkFactory
    {
        private static ThreadLocal<IAppUnitOfWork> appUnitOfWorkThreadLocal = new ThreadLocal<IAppUnitOfWork>(() => CreateUnitOfWork());

        public static IAppUnitOfWork GetAppUnitOfWorkRepository()
        {
            // 如果当前线程的IAppUnitOfWork已被释放，需要重新创建
            if (appUnitOfWorkThreadLocal.Value == null)
            {
                appUnitOfWorkThreadLocal.Value = CreateUnitOfWork();
            }
            return appUnitOfWorkThreadLocal.Value;
        }

        private static IAppUnitOfWork CreateUnitOfWork()
        {
            //通过反射创建工作单元的实例，需要优化
            string path = "Framework.Domain.UnitOfWork.AppUnitOfWork" + "," + "Framework.Domain";
            Type o = Type.GetType(path);
            object obj = Activator.CreateInstance(o, true);
            IAppUnitOfWork unitOfWork = (IAppUnitOfWork)obj;
            return unitOfWork;
        }


    }
}
